#include "Socket.hpp"
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include "Session.hpp"

#include <fstream>
#include <string>
#include <memory>
#include <cstring>

#include <unistd.h>

using namespace Net_Work;
SessionManager onlineuser;

std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknow";
    }
}

std::string SuffixToType(const std::string &suffix)
{
    if (suffix == ".html" || suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".gif")
        return "image/gif";
    else
    {
        return "text/html";
    }
}

std::string HandlerHttpRequest(std::string &request)
{
    HttpRequest req;

    // 反序列化
    req.Deseralize(request);
    req.Parse();
    req.DebugHttp();
    int code = 200;

    std::string content = req.GetFileContent();
    if (content.empty())
    {
        code = 404;
        content = req.Get_404();
    }

    // code = 307;
    HttpResponse resp;

    // if (req.Url() == "/register")
    // {
    //     // username, password
    //     std::string sessionid = onlineuser.AddSession(username, password);
    //     std::string session = "Set-Cookie: sessionid = " + sessionid;
    //     resp.AddHeader(sessionid);
    // }
    // if (if (req.Url() == "Logined"))
    // {

    //     std::string sessionid;
    //     if (onlineuser.SearchSession(sessionid))
    //     {
    //     }
    //     resp.AddHeader(sessionid);
    // }

    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code));
    resp.MakeStatusLine();
    std::string content_len_str = "Content-Length: " + std::to_string(content.size()) + "\r\n";
    resp.AddHeader(content_len_str);
    std::string content_type_str = "Content-Type: " + SuffixToType(req.Suffix()) + "\r\n"; // 正文的类型
    resp.AddHeader(content_type_str);
    // std::string location = "location: https://www.qq.com/\r\n";
    // resp.AddHeader(location);

    std::string namecookie = "Set-Cookie: Username=792557231\r\n";
    resp.AddHeader(namecookie);
    std::string passwdcookie = "Set-Cookie: password=1314520\r\n";
    resp.AddHeader(passwdcookie);
    std::string statuscookie = "Set-Cookie: status=logined\r\n";
    resp.AddHeader(statuscookie);

    resp.AddContent(content);

    return resp.Serialize();
}

// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<Tcp_Server> svr(new Tcp_Server(localport, HandlerHttpRequest));

    svr->Loop();

    return 0;
}
